import * as zrender from 'zrender'
import Scale from './scale'
import Tick from './tick';
class Axis extends zrender.Group{
    constructor(config, chartData){
        super();
        this.config = {
            start: [100,500],
            XorY: 'x',
            length: 400,
            // 绑定第几个下标的数据
            dataIndex: 1,
            // 轴线样式
            lineStyle:{
                stroke: '#666'
            },
            axisName:{
                offset: [0, 0],
                style:{
                    text: ''
                }
            },
            // 返回要画哪些值
            tickValues: function(config, scale){
                if(config.scale.type === 'linear'){
                    let val = scale.min
                    let arr = [[val, scale.get(val)]];
                    for(var i = 0; i < 5; i++){
                        val += (scale.max - scale.min) / 5;
                        arr.push([val, scale.get(val)])
                    }
                    return arr
                }else{
                    return [];
                }
            },
        }
        this.chartData = chartData;
        zrender.util.merge(this.config, config, true)
        // 初始化比例尺
        this.scale = new Scale(this.config, this.chartData)
        this.initLine();
        // 根据scale计算绘制哪几个tick
        this.initTick();
    }

    // 相对坐标转换为全局坐标
    getRealPosition(pos){
        return [this.config.start[0] + pos[0], this.config.start[1] - pos[1]]
    }

    initLine(){
        let [x1, y1] = this.config.start
        // 相对坐标的终点
        this.end = this.getRealPosition([(this.config.XorY === 'x' ? this.config.length : 0),(this.config.XorY === 'y' ? this.config.length : 0)])
        this.line = new zrender.Line({
            shape:{
                x1,
                y1,
                x2: this.end[0],
                y2: this.end[1], 
            },
            style: this.config.lineStyle
        })
        this.line.name = 'line'
        this.add(this.line)

        let isX = (this.config.XorY === 'x')
        let axisName = new zrender.Text({
            x: this.end[0] + this.config.axisName.offset[0],
            y: this.end[1] + this.config.axisName.offset[1],
            style:{
                ...this.config.axisName.style,
                align: isX ? 'left' : 'center',
                verticalAlign: isX ? 'center' : 'bottom', 
            }
        })
        axisName.name = 'axisName'
        this.add(axisName)
    }

    initTick(){
        // 根据scale，计算tick是哪几个
        let ticks = this.config.tickValues(this.config, this.scale)
        // 绘制
        ticks.forEach((t, i)=>{
            this.add(new Tick(this.config, t, i))
        })
    }
}

export default Axis